var fuzerenId="all";
var fuzerenId="all";
var state="all";
jQuery(document).ready(function() {
	$('#kit-search-more').on('click', function() {
		$('.kit-search-mored').toggle();
	});
    bindFuzerenSelect2(); // 2018-9-18 chenbin: 新增，绑定负责人下拉框
    bindFuzerenSelect3();
    var col = [
	{
	checkbox: 'checkbox'
	},
	{
		title:'ID',
		field:'id',
		align: 'center',
		valign: 'middle',
		visible: false
	},
	{
		title:'购买日期',
		field:'purchaseDate',
		align: 'center',
		valign: 'middle',
		visible: false,
		formatter: function (value, row, index) {
			var date = new Date(row.purchaseDate);
			Y = date.getFullYear() + '-';
			M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
			D = date.getDate() + ' ';
			var result = Y+M+D;
			return result;
			}
	},
	{
		title:'试听日期',
		field:'auditionTime',
		align: 'center',
		valign: 'middle',
		formatter: function (value, row, index) {
//			var date = new Date(row.trylistenDate);
			var auditionTime = row.auditionTime;

			if (auditionTime != null) {
				var auditionDate = auditionTime.substring(0,10);
				return auditionDate;
			}
//			var date = new Date(auditionDate);
//			Y = date.getFullYear() + '-';
//			M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
//			D = date.getDate() + ' ';
//			var result = Y+M+D; 
//			return result;
			return auditionTime;
			}
	},
	{
		title:'英文名',
		field:'enName',
		align: 'center',
		valign: 'middle',
        formatter: function (value, row, index) {
            return '<a href="javascript:;" style="color: red;" onclick="detail(\''+row.studentId+'\')">'+row.enName+'</a>';
        }
	},
	{
		title:'Zoom ID',
		field:'zoomId',
		align: 'center',
		valign: 'middle'
	},
	{
		title:'年龄',
		field:'age',
		align: 'center',
		valign: 'middle'
	},
	{
		title:'skype账号',
		field:'skypeId',
		align: 'center',
		valign: 'middle',
		visible: false
	},
	{
		title:'外教',
		field:'teacherName',
		align: 'center',
		valign: 'middle'
	},
	{
		title:'课程',
		field:'courseName',
		align: 'center',
		valign: 'middle'
	},
	{
		title:'试听类型',
		field:'trylistenType',
		align: 'center',
		valign: 'middle'
	},
	{
		title:'状态',
		field:'nowState',
		align: 'center',
		valign: 'middle'
	},
	{
		title:'录像',
		field:'recordVideo',
		align: 'center',
		valign: 'middle'
	},
	{
		title:'跟进结果',
		field:'followUp',
		align: 'center',
		valign: 'middle'
	},
	{
		title:'负责人',
		field:'fuzerenName',
		align: 'center',
		valign: 'middle'
	},
	{
		title:'推荐人',
		field:'recommand',
		align: 'center',
		valign: 'middle',
        formatter: function (value, row, index) {
            if(typeof row.recommand == "undefined" || row.recommand == null || row.recommand == ""){
                return '-';
            }else {
                return row.recommand;
            }
        }
	},
	{
		title:'备注',
		field:'remark',
		align: 'center',
		valign: 'middle'
	},
	{
		title: '操作',
	    formatter: function (value, row, index) {
	    	console.log('row', row);
	    	if(row.nowState=='已完成'){

				if(row.video !=null){
					return '<a href="javascript:;" onclick="edit(\''+row.id+'\',\''+row.studentId+'\',\''+row.teacherId+'\',\''+row.enName+'\',\''+row.course+'\')" class="layui-btn layui-btn-sm layui-btn">编辑</a>'+
						   '<a href="javascript:;" onclick="stateEdit(\''+row.id+'\')" class="layui-btn layui-btn-sm layui-btn">状态</a>'+
						   '<a href="javascript:;" onclick="followup(\''+row.id+'\')" class="layui-btn layui-btn-sm layui-btn">跟进</a>'+
						   '<a href="javascript:;" onclick="report(\''+row.id+'\')" class="layui-btn layui-btn-sm layui-btn">报告</a>'+
                           '<a href="javascript:;" class="layui-btn layui-btn-sm" onclick="getCourselogRecording(\'' + row.id + '\')">视频</a>'+
						   '<a href="javascript:;" onclick="doDelete(\''+row.id+'\')" class="layui-btn layui-btn-sm layui-btn-danger">删除</a>';
				}
                return '<a href="javascript:;" onclick="edit(\''+row.id+'\',\''+row.studentId+'\',\''+row.teacherId+'\',\''+row.enName+'\',\''+row.course+'\')" class="layui-btn layui-btn-sm layui-btn">编辑</a>'+
                       '<a href="javascript:;" onclick="stateEdit(\''+row.id+'\')" class="layui-btn layui-btn-sm layui-btn">状态</a>'+
                       '<a href="javascript:;" onclick="followup(\''+row.id+'\')" class="layui-btn layui-btn-sm layui-btn">跟进</a>'+
                       '<a href="javascript:;" onclick="report(\''+row.id+'\')" class="layui-btn layui-btn-sm layui-btn">报告</a>'+
                       '<a href="javascript:;" onclick="doDelete(\''+row.id+'\')" class="layui-btn layui-btn-sm layui-btn-danger">删除</a>';

            }else {
                if(row.video !=null) {
                    return '<a href="javascript:;" onclick="edit(\''+row.id+'\',\''+row.studentId+'\',\''+row.teacherId+'\',\''+row.enName+'\',\''+row.course+'\')" class="layui-btn layui-btn-sm layui-btn">编辑</a>'+
                           '<a href="javascript:;" onclick="stateEdit(\''+row.id+'\')" class="layui-btn layui-btn-sm layui-btn">状态</a>'+
                           '<a href="javascript:;" onclick="return false;"  style="background-color:#999" class="layui-btn layui-btn-sm layui-btn">跟进</a>'+
                           '<a href="javascript:;" onclick="report(\''+row.id+'\')" class="layui-btn layui-btn-sm layui-btn">报告</a>'+
                           '<a href="javascript:;" class="layui-btn layui-btn-sm" onclick="getCourselogRecording(\'' + row.id + '\')">视频</a>'+
                           '<a href="javascript:;" onclick="doDelete(\''+row.id+'\')" class="layui-btn layui-btn-sm layui-btn-danger">删除</a>';
                }
                return '<a href="javascript:;" onclick="edit(\''+row.id+'\',\''+row.studentId+'\',\''+row.teacherId+'\',\''+row.enName+'\',\''+row.course+'\')" class="layui-btn layui-btn-sm layui-btn">编辑</a>'+
                       '<a href="javascript:;" onclick="stateEdit(\''+row.id+'\')" class="layui-btn layui-btn-sm layui-btn">状态</a>'+
                       '<a href="javascript:;" onclick="return false;"  style="background-color:#999" class="layui-btn layui-btn-sm layui-btn">跟进</a>'+
                       '<a href="javascript:;" onclick="report(\''+row.id+'\')" class="layui-btn layui-btn-sm layui-btn">报告</a>'+
                       '<a href="javascript:;" onclick="doDelete(\''+row.id+'\')" class="layui-btn layui-btn-sm layui-btn-danger">删除</a>';
			}

	    } //自定义方法，添加操作按钮
	}];

	//------------------------------------------加载列表
	$('#_table').bootstrapTable({
		url:baseUrl+'/trylistenmanages',
		'method': "GET",
		locale: 'zh-CN',
		detailView: false,
		sidePagination: "server",
		striped: true,//隔行变色
		undefinedText: "",
		pagination: true,
		singleSelect: false,
		pageSize: pageList[0],
		cache: false,
		pageNumber: 1,
		pageList: pageList,
		search: false,
		uniqueId: "id",
		showColumns: true,
		undefinedText: '',
		columns: col,
		showRefresh:true,
		queryParams: function(params) {
			return {
				pageNum: this.pageNumber,
				pageSize: this.pageSize,
				sortOrder: params.order
			}
		},

	});

    // 2018-10-11 chenbin: 下拉框条件查询
    // document.getElementById("_fuzerenSelect").onchange=function(){
    //     fuzerenId = this.value;
    //     var selectCondition;
    //     if(fuzerenId=="all"){
    //         $("#_table").bootstrapTable('refresh',{url :baseUrl+ '/trylistenmanages'});
    //     }
    //     else{
    //         selectCondition = fuzerenId;
    //         $("#_table").bootstrapTable('refresh',{url :baseUrl+ '/trylistenmanages/selectByCondition/' + selectCondition });
    //     }
    // };

    // 2018-10-11 chenbin: 下拉框条件查询
    // document.getElementById("_fuzerenSelect").onchange = function () {
    //     fuzerenId = this.value;
    //     var selectCondition;
    //     if (fuzerenId == "all" && state == "all") {
    //         $("#_table").bootstrapTable('refresh', {url: baseUrl + '/freeAuditions'});
    //     }
    //     else {
    //         selectCondition = fuzerenId + "&" + state;
    //         $("#_table").bootstrapTable('refresh', {url: baseUrl + '/freeAuditions/selectByCondition/' + selectCondition});
    //     }
    // };
    // document.getElementById("_stateSelect").onchange = function () {
    //     state = this.value;
    //     var selectCondition;
    //     if (fuzerenId == "all" && state == "all") {
    //         $("#_table").bootstrapTable('refresh', {url: baseUrl + '/freeAuditions'});
    //     }
    //     else {
    //         selectCondition = fuzerenId + "&" + state;
    //         $("#_table").bootstrapTable('refresh', {url: baseUrl + '/freeAuditions/selectByCondition/' + selectCondition});
    //     }
    // };

    // $("select#_fuzerenSelect").change(function(){
    //     var stid = $('#_fuzerenSelect option:selected').text();//选中的文本
    //     alert(stid);
    //     var name = stid.split('     ')[1]
    //     alert(name);
    //     $("#_fuzerenSelect").val(name);
    // });

})

function getCourselogRecording(id) {
    parent.layer.open({
                          //				title: false,
                          maxmin: true,
                          type: 2,
                          area: modalArea,
                          content: './views/form/CurriculumScheduleViewEdit1.html?id=' + id+"&type=2", //这里content是一个URL，如果你不想让iframe出现滚动条，你还可以content:
                                                                                             // ['http://sentsin.com',
                                                                                             // 'no']
                          btn: ['保存', '取消'],
                          yes: function (index, layero) {
                              var data = $(layero).find("iframe")[0].contentWindow.callback_save();
                              console.log(layero);
                              $.ajax({
                                         url: baseUrl + '/curriculumSchedules/' + id,
                                         type: 'post',
                                         data: data,
                                         success: function (data) {
                                             alert(data.msg);
                                             parent.layer.close(index);
                                             $('#_table').bootstrapTable('refresh');

                                             $.ajax({
                                                        url: baseUrl + '/purchaseCourseViews/' + purchaseCourseId,
                                                        type: 'get',
                                                        async: false,
                                                        success: function (datas) {
                                                            console.log(datas);
                                                            var data = datas.data;
                                                            data.hoursEnrolled = data.hoursEnrolled / 60;
                                                            data.hoursRemaining = data.hoursRemaining / 60;
                                                            data.hoursCompleted = data.hoursCompleted / 60;
                                                            data.hourShengyu = data.hoursEnrolled - data.hoursRemaining;

                                                            $.link(true, ".layui-form", data);
                                                        }
                                                    });

                                         }
                                     });
                          },
                          btn2: function (index, layero) {
                          }
                      });
}


// 2018-9-18 chenbin: 新增，绑定负责人下拉框
function bindFuzerenSelect2() {
    // var fuzerenData = [];
    // $.ajax({
    //     type : "get",
    //     url :baseUrl+ '/students/select2',
    //     async : false,
    //     success : function(data) {
    //         fuzerenData = data;
    //     }
    // });
    //
    // $('#_fuzerenSelect').select2({
    //     data : fuzerenData
    // });
    $("#_fuzerenSelect").select2({
        ajax: {
            type: "get",
            url: baseUrl + '/students/select4',
            dataType: 'json',
            delay: 250,
			placeholder : '选择学生', //placeholder
            data: function (params) {
                return {
                    key: params.term,
                };
            },
            processResults: function (data) {
                return {
                    results: data
                };
            },
            cache: true
        },
        escapeMarkup: function (markup) {
            return markup;
        },
        minimumInputLength: 1,
        templateResult: function (data, container) {
            var $result = $("<span></span>");
            $result.text(data.showline);
            return $result;
        }
    });


}

function bindFuzerenSelect3() {
    var fuzerenData = [];
    $.ajax({
        type : "get",
        url : baseUrl+'/admins/select2',
        async : false,
        success : function(data) {
            fuzerenData = data;
//			fuzerenData.unshift({
//				id : 'all',
//				text : '请选择'
//			});
        }
    });
    $('#_fuzerenSelect1').select2({
        data : fuzerenData
    });
}


var detail = function(uid) {
    parent.layer.open({
        //				title: false,
        maxmin: true,
        type: 2,
        area: modalArea,
        content: './views/form/StudentsDetail.html?studentId='+uid, //这里content是一个URL，如果你不想让iframe出现滚动条，你还可以content: ['http://sentsin.com', 'no']
        btn: [ '关闭'],
        btn2: function(index, layero) {
        }
    });
}

var searchForm = function () {
    var data = $('.layui-form').serialize();
    $("#_table").bootstrapTable('refresh',{url:baseUrl+ '/trylistenmanages?'+data });
}

// 添加新课程
var addTryListen = function(){
	parent.layer.open({
		maxmin: true,
		type: 2,
		area: ['600px','600px'],
		content: './views/form/TryListenAdd.html',
		btn: ['保存', '取消'],
		yes: function(index, layero) {
			var data = $(layero).find("iframe")[0].contentWindow.callback_save();
			console.log(layero);
			$.ajax({
				url:baseUrl+ '/trylistenmanages',
				type: 'POST',
				data: data,
				success: function(data) {
					alert(data.msg);
					parent.layer.close(index);
					$('#_table').bootstrapTable('refresh');
				}
			});
		},
		btn2: function(index, layero) {
			//按钮【按钮二】的回调
			console.log(layero);
			//return false 开启该代码可禁止点击该按钮关闭
		}
	});


}
var searchFun = function() {
	alert("search");
};

// 2018-9-24 chenbin: 跟进
function followup(uniqueId){
	parent.layer.open({
		maxmin: true,
		type: 2,
		area: ['400px','400px'],
		content: './views/form/followupTrylistenmanage.html?uniqueId='+uniqueId,
		btn: ['保存', '取消'],
		yes: function(index, layero) {
			var data = $(layero).find("iframe")[0].contentWindow.callback_save();
			var reg = RegExp(/all/);
			var postMsg=uniqueId+"&"+data+"extra";
			if(reg.test(data)){
				alert("请选择跟进状态后保存");
				parent.layer.close(index);
				$('#_table').bootstrapTable('refresh');
				return;
			}
			$.ajax({
				url:baseUrl+ '/trylistenmanages/saveRemark/',
				type: 'POST',
				data:{
		            postMsg:postMsg
		        },
				success: function(data) {
					alert(data.msg);
					parent.layer.close(index);
					$('#_table').bootstrapTable('refresh');
				}
			});
		},
		btn2: function(index, layero) {
		}
	});
}

// 2018-9-27 chenbin: 编辑
function edit(uniqueId,studentId,teacherId,enName,course){
//	alert(uniqueId);
	parent.layer.open({
		maxmin: true,
		type: 2,
		area: ['600px','600px'],
		content: './views/form/editTryListen.html?uniqueId='+uniqueId+'&techerid='+teacherId+'&studentid='+studentId+'&studentName='+encodeURI(enName)+'&course='+course,
		btn: ['保存', '取消'],
		yes: function(index, layero) {
			var data = $(layero).find("iframe")[0].contentWindow.callback_save2();
            // var reg = RegExp(/all/);
			// uid=uniqueId+"&"+data+"extra";
			// if(reg.test(data)){
			// 	alert("请选择跟进状态后保存");
			// 	parent.layer.close(index);
			// 	$('#_table').bootstrapTable('refresh');
			// 	return;
			// }

			$.ajax({
				url: baseUrl+'/trylistenmanages/update',
				type: 'POST',
                data: data,
                success: function(data) {
                    parent.layer.close(index);
                    $('#_table').bootstrapTable('refresh');
					// parent.layer.close(index);
					// $('#_table').bootstrapTable('refresh');
				}
			});
		},
		btn2: function(index, layero) {
		}
	});
}

// 2018-9-27 chenbin: “状态”管理
function stateEdit(uniqueId){
	//alert("状态");
	parent.layer.open({
		maxmin: true,
		type: 2,
		area: ['300px','300px'],
		content: './views/form/StateListenmanage.html?uniqueId='+uniqueId,
		btn: ['保存', '取消'],
		yes: function(index, layero) {
			var data = $(layero).find("iframe")[0].contentWindow.callback_save();
			var postMsg=uniqueId+"&"+data;
			if(data=="all"){
				alert("请选择状态后保存");
				parent.layer.close(index);
				$('#_table').bootstrapTable('refresh');
				return;
			}
			$.ajax({
				url:baseUrl+ '/trylistenmanages/savestateEdit1',
				type: 'GET',
				data:{
		            postMsg:encodeURI(postMsg)
		        },
				success: function(data) {
                    if (data.data == null) {
                        alert("状态更新失败");
                    } else {
                        parent.layer.close(index);
                        $('#_table').bootstrapTable('refresh');
                    }
				}
			});
		},
		btn2: function(index, layero) {
		}
	});
}

//此函数为测试函数，根据uid获取trylistenmanageview视图数据
function test(uniqueId){

	$.ajax({
		url:baseUrl+ '/trylistenmanages/getByUid/'+uniqueId,
		type: 'GET',
		success: function(data) {
			//alert(data.data);
		}
	});
}

function report(id){
    parent.layer.open({
        //title: false,
        maxmin: true,
        type: 2,
        area: modalArea,
        content: './views/form/TrialClassReport.html?id='+id,
        area: ['703.5px', '865px'],
        btn: ['关闭'],
        // yes: function(index, layero) {
        //     var data = $(layero).find("iframe")[0].contentWindow.callback_save();
        //     console.log(layero);
        //     // $.ajax({
        //     //     url:baseUrl+ '/trylistenmanages/report/'+id,
        //     //     type: 'POST',
        //     //     data: data,
        //     //     area: ['800px', '600px'],
        //     //     success: function(data) {
        //     //         parent.layer.close(index);
        //     //         $('#_table').bootstrapTable('refresh');
        //     //     }
        //     // });
        // },
        btn2: function(index, layero) {
            //按钮【按钮二】的回调
            console.log(layero);
            //return false 开启该代码可禁止点击该按钮关闭
        }
    });
}

function getVideo(uniqueId){
	alert("获取视频功能开发中……");
}

//删除
function doDelete(uniqueId){
	 if(window.confirm('你确定要删除数据吗？')){
		 $.ajax({
				url:baseUrl+ '/trylistenmanages/savedoDelete/'+uniqueId,
				type: 'GET',
				success: function(data) {
					alert(data.msg);
					$('#_table').bootstrapTable('refresh');
				}
			});

		 }
	 else{
		 alert("已取消删除");
	}
}




function doSearch(){
	var searchConditon = $('#searchText').val();
	if(searchConditon){
		$("#_table").bootstrapTable('refresh',{url : baseUrl+'/trylistenmanages/getByConditon/'+searchConditon });
	}
	else{
		$("#_table").bootstrapTable('refresh',{url : baseUrl+'/trylistenmanages' });
	}
//	$.ajax({
//		url: '/trylistenmanages/getByConditon/'+searchConditon,
//		type: 'GET',
//		success: function(data) {
//			alert(1111);
//		}
//	});	
}


// 2018-10-11 chenbin: 下拉框条件查询
// document.getElementById("_fuzerenSelect1").onchange = function () {
//     fuzerenId = this.value;
//     var selectCondition;
//     if (fuzerenId == "all" && state == "all") {
//         $("#_table").bootstrapTable('refresh', {url: baseUrl + '/freeAuditions'});
//     }
//     else {
//         selectCondition = fuzerenId + "&" + state;
//         $("#_table").bootstrapTable('refresh', {url: baseUrl + '/freeAuditions/selectByCondition/' + selectCondition});
//     }
// };


//var check = function() {
//
//}
//var doDelete = function() {
//	var rows = $('#_table').bootstrapTable('getSelections');
//	if(rows == [] || rows == null || rows.length == 0) {
//		parent.layer.alert('请�?�择要编辑的数据�?', {
//			skin: 'layui-layer-molv', //样式类名
//			closeBtn: 0,
//			anim: 4,
//			time: 2000
//		});
//		return;
//	}
//	if(rows.length != 1) {
//		parent.layer.alert('请�?�择单条数据进行编辑�?', {
//			skin: 'layui-layer-molv', //样式类名
//			closeBtn: 0,
//			anim: 4,
//			time: 1800
//		});
//		return;
//	}
//	$.ajax({
//		type: "delete",
//		url: '/trylistenmanages/' + rows[0].id,
//		async: true,
//		success: function(data) {
//			alert(data.msg);
//			$('#_table').bootstrapTable('refresh');
//		}
//	});
//}
//var insert = function() {
//	parent.layer.open({
//		//				title: false,
//		maxmin: true,
//		type: 2,
//		area: modalArea,
//		content: './views/form/TrylistenmanageEdit.html',
//		btn: ['保存', '取消'],
//		yes: function(index, layero) {
//			var data = $(layero).find("iframe")[0].contentWindow.callback_save();
//			console.log(layero);
//			$.ajax({
//				url: '/trylistenmanages',
//				type: 'POST',
//				data: data,
//				success: function(data) {
//					alert(data.msg);
//					parent.layer.close(index);
//					$('#_table').bootstrapTable('refresh');
//				}
//			});
//		},
//		btn2: function(index, layero) {
//			//按钮【按钮二】的回调
//			console.log(layero);
//			//return false �?启该代码可禁止点击该按钮关闭
//		}
//	});
//}
//
//var edit = function() {
//	var rows = $('#_table').bootstrapTable('getSelections');
//	if(rows == [] || rows == null || rows.length == 0) {
//		parent.layer.alert('请�?�择要编辑的数据�?', {
//			skin: 'layui-layer-molv', //样式类名
//			closeBtn: 0,
//			anim: 4,
//			time: 2000
//		});
//		return;
//	}
//	if(rows.length != 1) {
//		parent.layer.alert('请�?�择单条数据进行编辑�?', {
//			skin: 'layui-layer-molv', //样式类名
//			closeBtn: 0,
//			anim: 4,
//			time: 1800
//		});
//		return;
//	}
//	parent.layer.open({
//		//				title: false,
//		maxmin: true,
//		type: 2,
//		area: modalArea,
//		content: './views/form/TrylistenmanageEdit.html?id='+rows[0].id, //这里content是一个URL，如果你不想让iframe出现滚动条，你还可以content: ['http://sentsin.com', 'no']
//		btn: ['保存', '取消'],
//		yes: function(index, layero) {
//			var data = $(layero).find("iframe")[0].contentWindow.callback_save();
//			console.log(layero);
//			$.ajax({
//				url:'/trylistenmanages/'+rows[0].id,
//				type: 'POST',
//				data: data,
//				success: function(data) {
//					alert(data.msg);
//					parent.layer.close(index);
//					$('#_table').bootstrapTable('refresh');
//				}
//			});
//		},
//		btn2: function(index, layero) {
//			//按钮【按钮二】的回调
//			alert(index);
//			console.log(layero);
//			//return false �?启该代码可禁止点击该按钮关闭
//		}
//	});
//}
